<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter, RouterLink } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const cart = useCartStore()
const product = useProductStore()
const user = useUserStore()
const q = ref('')

onMounted(() => {
  if (!product.categories.length) product.fetchCategories()
})

watch(() => user.isLogin, (val) => {
  if (val) {
    // 登录成功后，重新拉取分类，避免未登录导致的空数据
    product.fetchCategories()
  }
})

function search() {
  router.push({ name: 'home', query: { q: q.value } })
}
</script>

<template>
  <header class="site-header">
    <div class="inner">
      <RouterLink to="/" class="brand">
        <img alt="logo" src="/favicon.ico" />
        <span>点三商城</span>
      </RouterLink>
      <div class="search">
        <input v-model="q" type="text" placeholder="搜索商品" @keyup.enter="search" />
        <button @click="search">搜索</button>
      </div>
  <nav class="nav">
    <RouterLink to="/">首页</RouterLink>
    <RouterLink to="/category">分类</RouterLink>
    <RouterLink to="/cart">购物车({{ cart.totalCount }})</RouterLink>
    <RouterLink v-if="!user.isLogin" to="/login">登录/注册</RouterLink>
    <span v-else>
      欢迎，{{ user.session.userId }}
      <a href="#" @click.prevent="user.clear()">退出</a>
    </span>
  </nav>
    </div>
  </header>
</template>

<style scoped>
.site-header {
  border-bottom: 1px solid #eee;
  background: #fff;
}
.inner {
  max-width: var(--page-max);
  margin: 0 auto;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}
.brand {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: #333;
  text-decoration: none;
  font-weight: 600;
}
.brand img { width: 24px; height: 24px; }
.search { flex: 1; display: flex; gap: 8px; }
.search input { width: 100%; padding: 8px 10px; border: 1px solid #ddd; border-radius: 4px; }
.search button { padding: 8px 12px; border: 1px solid #ddd; background: #f7f7f7; border-radius: 4px; }
.nav { display: flex; gap: 12px; }
.nav a { color: #333; text-decoration: none; }
.nav a.router-link-active { color: #42b883; }
</style>